package org.learn.simple.file.server.handlers;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.DefaultFileRegion;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpRequest;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author <a href="mailto:675464934@qq.com">Terrdi</a>
 * @date 2021/12/19
 * @since 1.8
 **/
public class SearchFileHandler extends SimpleChannelInboundHandler<HttpRequest> {
    private final String basePath;

    public SearchFileHandler(String basePath) {
        this.basePath = basePath;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpRequest request) throws Exception {
        String uri = URLDecoder.decode(request.uri(), "UTF-8");
        File file = new File(this.basePath, uri);
        if (file.isDirectory()) {
            List<String> list = new ArrayList<>(10);
            Arrays.stream(file.listFiles()).map(File::getName).forEachOrdered(list::add);
            ctx.writeAndFlush(list);
        } else {
            ctx.writeAndFlush(file);
        }
    }
}
